package com.hc.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author LiuZhiHao
 * @date 2019/12/9 11:38
 * 描述:
 **/
public class DateUtil {

    private static SimpleDateFormat simpleDateFormatH = new SimpleDateFormat("yyyy-MM-dd");

    private static SimpleDateFormat simpleDateFormatS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static String getBeforeZero() {
        Date date = new Date();
        //获取指定时间点
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        String format = simpleDateFormatH.format(date);
        return format + " 00:00:00";
    }

    public static String getEndOfDay(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = null;
        try {
            parse = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return  simpleDateFormat.format(parse)+" 23:59:59";
    }

    public static String getBeforeEight() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        String format = simpleDateFormatH.format(date);
        return format + " 00:00:00";
    }

    public static String getAddAfterTime(String time, int hours) {
        Date parse = null;
        try {
            parse = simpleDateFormatS.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(parse);
        cal.add(Calendar.HOUR, hours);
        Date time1 = cal.getTime();
        return simpleDateFormatS.format(time1);
    }

    public static Date getAddAfterDate(String time, int hours) {
        Date parse = null;
        try {
            parse = simpleDateFormatS.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(parse);
        cal.add(Calendar.HOUR, hours);
        return cal.getTime();
    }


    public static double divide(double a, double b, int scale) {
        BigDecimal bd1 = new BigDecimal(Double.toString(a));
        BigDecimal bd2 = new BigDecimal(Double.toString(b));
        return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 以 yyyy-MM-dd HH:mm:ss 的格式解析String
     *
     * @param str
     * @return
     */
    public static Date parseDate(String str) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date;
        try {
            date = simpleDateFormat.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }

    /**
     * 将yyyy-MM-dd格式的字符串转化成LocalDateTime类型
     *
     * @param dateStr
     * @return
     */
    public static LocalDateTime changeStrToDateTime(String dateStr) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(dateStr, df);
        LocalDateTime localDateTime = localDate.atStartOfDay();
        return localDateTime;
    }

    /**
     * 计算开始时间和结束时间间隔了多少天
     *
     * @param beginDateStr
     * @param endDateStr
     * @return
     */
    public static Long countDate(String beginDateStr, String endDateStr) {
        LocalDateTime beginTime = changeStrToDateTime(beginDateStr);
        LocalDateTime endTime = changeStrToDateTime(endDateStr);
        Duration duration = Duration.between(beginTime, endTime);
        long l = duration.toDays();
        return l;
    }

    public static String paseDate(Date time){
        return simpleDateFormatH.format(time);
    }

    public static void main(String[] args) {
//        String beforeZero = DateUtil.getBeforeZero();
//        for (int i = 1; i <= 8; i++) {
//            String addAfterTime1 = DateUtil.getAddAfterTime(beforeZero, (i - 1) * 3);
//            String addAfterTime = DateUtil.getAddAfterTime(beforeZero, i * 3);
//            System.out.println(addAfterTime1 + "------------------冰箱------------------------" + addAfterTime);
//        }
//
//        for (int i = 1; i <= 4; i++) {
//            String addAfterTime1 = DateUtil.getAddAfterTime(beforeZero, (i - 1) * 6);
//            String addAfterTime = DateUtil.getAddAfterTime(beforeZero, i * 6);
//            System.out.println(addAfterTime1 + "------------------培养箱-----------------------" + addAfterTime);
//        }
//        String beforeEight = DateUtil.getBeforeEight();
//        for (int i = 1; i <= 4; i++) {
//            String addAfterTime1 = DateUtil.getAddAfterTime(beforeEight, (i - 1) * 6);
//            String addAfterTime = DateUtil.getAddAfterTime(beforeEight, i * 6);
//            System.out.println(addAfterTime1 + "------------------环境-----------------------" + addAfterTime);
//        }
        //String addAfterTime = DateUtil.getAddAfterTime("2024-01-08 00:00:00", 24);
        List<String> betweenDates = getBetweenDates("2023-01-03 00:00:00", "2023-04-09 00:00:00", true);
        System.out.println(betweenDates);
    }

    public static String getCurrentYearMonth() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        //日历类的月份为0-11 所以要加1
        int month = cal.get(Calendar.MONTH)+1;
        return ""+year+month;
    }

    /**
     * 获取前一天的数据
     * @return
     */
    public static String getThePreviousDayYearMonth(){
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE,-1);
        int year = cal.get(Calendar.YEAR);
        //日历类的月份为0-11 所以要加1
        int month = cal.get(Calendar.MONTH)+1;
        return ""+year+month;
    }


    public static String getBeforeDay() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //获取指定时间点
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        date = calendar.getTime();
        String format = simpleDateFormat.format(date);
        return format;
    }

    /**
     * 当前时间是否在此时间区间时分内
     * （只在同月生效）,只在同月生效,只在同月生效 重要 说三遍
     * 例如： 2022-11-12 01:00:00(nowTime)   2022-11-11 00:00:00(startTime) 2022-11-11 02:00:00(endTime) true
     *
     * @param nowTime
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean whetherItIsIn(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        date.set(Calendar.YEAR, 2022);
        date.set(Calendar.MONTH, 1);
        date.set(Calendar.DATE, 1);
        Date time1 = date.getTime();

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);
        begin.set(Calendar.YEAR, 2022);
        begin.set(Calendar.MONTH, 1);
        begin.set(Calendar.DATE, 1);
        Date time2 = begin.getTime();

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        end.set(Calendar.YEAR, 2022);
        end.set(Calendar.MONTH, 1);
        end.set(Calendar.DATE, 1);
        Date time3 = end.getTime();
        //统一年月日后对比
        if (time1.after(time2) && time1.before(time3)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 补全给定起止时间区间内的所有日期
     * @param startTime
     * @param endTime
     * @param isIncludeStartTime
     * @return
     */
    public static List<String> getBetweenDates(String startTime, String endTime, boolean isIncludeStartTime){
        List<String> result = new ArrayList<>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime);//定义起始日期
            Date d2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime);//定义结束日期  可以去当前月也可以手动写日期。
            Calendar dd = Calendar.getInstance();//定义日期实例
            dd.setTime(d1);//设置日期起始时间
            if(isIncludeStartTime) {
                result.add(format.format(d1));
            }
            while (dd.getTime().before(d2)) {//判断是否到结束日期
                dd.add(Calendar.DATE, 1);//进行当前日期加1
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String str = sdf.format(dd.getTime());
                result.add(str);
                System.out.println(str);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 格式化日期字符串为完整格式 yyyy-MM-dd HH:mm:ss
     * 支持以下格式的输入：
     * 1. yyyy-MM-dd HH:mm:ss (直接返回)
     * 2. yyyy-MM-dd (补充 00:00:00)
     * 3. yyyyMMdd (转换为 yyyy-MM-dd 00:00:00)
     */
    public static String formatDateString(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            throw new IllegalArgumentException("日期参数不能为空");
        }
        dateStr = dateStr.trim();
        // 如果已经是完整格式，直接返回
        if (dateStr.length() == 19 && dateStr.contains(":")) {
            return dateStr;
        }
        // 处理 yyyy-MM-dd 格式
        if (dateStr.length() == 10 && dateStr.contains("-")) {
            return dateStr + " 00:00:00";
        }
        // 处理 yyyyMMdd 格式
        if (dateStr.length() == 8 && !dateStr.contains("-")) {
            try {
                // 解析为数字确保是有效的日期数字
                Long.parseLong(dateStr);
                return dateStr.substring(0, 4) + "-" + dateStr.substring(4, 6) + "-" + dateStr.substring(6, 8) + " 00:00:00";
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("无效的日期格式: " + dateStr);
            }
        }
        throw new IllegalArgumentException("不支持的日期格式: " + dateStr);
    }
}
